<!DOCTYPE html>
<html lang="en-us">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <title> Date/Time </title>

  <link rel="stylesheet" media="screen" href="/css/style.css" >
</head>
<body>

  <header class="site-header">
    <h3 class="site-title">
      <a href="https://mkaz.github.io/working-with-go/">
        Working with Go
      </a>
    </h3>
  </header>

  <main>

    <aside>
      <h2>Contents</h2>
      <ul>
        
          <li><a href="/hello.html">Hola Mundo</a></li>
        
          <li><a href="/strings.html">Strings</a></li>
        
          <li><a href="/slices.html">Slices</a></li>
        
          <li><a href="/functions.html">Functions</a></li>
        
          <li><a href="/control-structures.html">Control Structures</a></li>
        
          <li><a href="/for-loops.html">For Loops</a></li>
        
          <li><a href="/structs.html">Structs</a></li>
        
          <li><a href="/maps.html">Maps</a></li>
        
          <li><a href="/files.html">Files</a></li>
        
          <li><a href="/read-dir.html">Directories</a></li>
        
          <li><a href="/objects.html">Objects</a></li>
        
          <li><a href="/command-line.html">Command-line</a></li>
        
          <li><a href="/date-time.html">Date/Time</a></li>
        
          <li><a href="/sorting.html">Sorting</a></li>
        
          <li><a href="/json.html">JSON</a></li>
        
          <li><a href="/web-server.html">Web Server</a></li>
        
          <li><a href="/guess-game.html">Guessing Game</a></li>
        
          <li><a href="/rest-api.html">REST API</a></li>
        
          <li><a href="/regexps.html">Regexp</a></li>
        
          <li><a href="/memcache.html">Memcache</a></li>
        
          <li><a href="/mysql.html">MySQL</a></li>
        
          <li><a href="/interfaces.html">Interfaces</a></li>
        
          <li><a href="/testing.html">Testing</a></li>
        
      </ul>
    </aside>

    <article class="entry-content">
      <h1>Working with Date and Time</h1>

<p>The <a href="http://golang.org/pkg/time/"><code>time</code></a> standard library provides the methods needed for working with dates and time in Go.</p>

<h2>Now</h2>

<p>Create a date using <code>time.Now()</code>, returns a <code>Time</code> type</p>

<pre><code class="language-go">now := time.Now()
</code></pre>

<p>Create a Unix timestamp, returns a <code>int64</code> type</p>

<pre><code class="language-go">unix := time.Unix()
</code></pre>

<h2>Format Date</h2>

<p>Go uses a format-by-example method for formating dates. This is odd and you may never get used to it, I still haven&rsquo;t. There is a base date <code>Monday, January 2nd, 2006 at 15:04:05</code> and all formats specified are based off examples using that date.</p>

<p>If you want a date in <code>YYYY-MM-DD</code> format, you would use <code>2006-01-02</code> as the format string.</p>

<p>It is debatable what is easier to remember? The sample date or the <code>%b %c</code> formats other languages use. A way to try to remember is <code>Month=1, Day=2, Hour=3, Minute=4, Sec=5, Year=6</code></p>

<pre><code class="language-go">fmt.Println(now.Format(&quot;Mon, Jan 2, 2006 at 3:04pm&quot;))
</code></pre>

<p>Use a method to get any part of the date, see <a href="http://golang.org/pkg/time/#Time"><code>Time</code></a> documentation for list of available time methods.</p>

<pre><code class="language-go">fmt.Println(&quot;Year: &quot;, now.Year())
fmt.Println(&quot;Month: &quot;, now.Month())
</code></pre>

<h2>Built-in Formats</h2>

<p>The time library contains a set of <a href="http://golang.org/pkg/time/#pkg-constants">built-in constants</a> to assist with standard date formatting.</p>

<pre><code>const (
	ANSIC       = &quot;Mon Jan _2 15:04:05 2006&quot;
	UnixDate    = &quot;Mon Jan _2 15:04:05 MST 2006&quot;
	RubyDate    = &quot;Mon Jan 02 15:04:05 -0700 2006&quot;
	RFC822      = &quot;02 Jan 06 15:04 MST&quot;
	RFC822Z     = &quot;02 Jan 06 15:04 -0700&quot; // RFC822 with numeric zone
	RFC850      = &quot;Monday, 02-Jan-06 15:04:05 MST&quot;
	RFC1123     = &quot;Mon, 02 Jan 2006 15:04:05 MST&quot;
	RFC1123Z    = &quot;Mon, 02 Jan 2006 15:04:05 -0700&quot; // RFC1123 with numeric zone
	RFC3339     = &quot;2006-01-02T15:04:05Z07:00&quot;
	RFC3339Nano = &quot;2006-01-02T15:04:05.999999999Z07:00&quot;
	Kitchen     = &quot;3:04PM&quot;
	// Handy time stamps.
	Stamp      = &quot;Jan _2 15:04:05&quot;
	StampMilli = &quot;Jan _2 15:04:05.000&quot;
	StampMicro = &quot;Jan _2 15:04:05.000000&quot;
	StampNano  = &quot;Jan _2 15:04:05.000000000&quot;
)
</code></pre>

<p>An example using the constant formats</p>

<pre><code class="language-go">fmt.Println(now.Format(time.RFC850))
fmt.Println(now.Format(time.RFC1123))
</code></pre>

<h2>Setting a Specific Date</h2>

<p>A time zone is required when specifying a date, you can build a time zone using the LoadLocation, or you could also use the <code>time.UTC</code> constant for UTC.</p>

<pre><code class="language-go">est, _ := time.LoadLocation(&quot;EST&quot;)
july4 := time.Date(1776, 7, 4, 12, 15, 0, 0, est)
</code></pre>

<h2>Parse Dates</h2>

<p>You can parse user inputted dates using known formats by specifying the format by example</p>

<pre><code class="language-go">input_format := &quot;1/2/2006 3:04pm&quot;
user_str := &quot;4/16/2014 11:38am&quot;
user_date, err := time.Parse(input_format, user_str)
if err != nil {
	fmt.Println(&quot;&gt;&gt;&gt; Error parsing date string&quot;)
}
fmt.Println(&quot;User Date: &quot;, user_date.Format(&quot;Jan 2, 2006 @ 3:04pm&quot;))
</code></pre>

<h2>Date/Time Comparisons</h2>

<p>You can use <code>Before()</code>, <code>After()</code>, or <code>Equal()</code> to compare dates.</p>

<pre><code class="language-go">if july4.Before(now) {
	fmt.Println(&quot;July 4 is before Now &quot;)
}
</code></pre>

<h2>Date Arithmetic</h2>

<p>The Time library also includes a <a href="https://golang.org/pkg/time/#Duration"><code>Duration type</code></a> which represents the different between two dates. The Duration type does not include days due to timezones and daylight savings.</p>

<p>Calculate a <code>Duration:</code></p>

<pre><code class="language-go">diff := now.Sub(july4)
</code></pre>

<p>Use a <code>Duration</code>:</p>

<pre><code class="language-go">fmt.Printf(&quot;July 4 was about %d hours ago \n&quot;, diff.Hours())
</code></pre>

<p>You can add dates using Durations</p>

<pre><code class="language-go">twodaysDiff := time.Hour * 24 * 2
twodays := now.Add(twodaysDiff)
fmt.Println(&quot;Two Days: &quot;, twodays.Format(time.ANSIC))
</code></pre>

    </article>

  </main>

<footer class="site-footer" role="contentinfo">
    An <a href="https://mkaz.blog/">mkaz</a> joint
    <span class="sep"> | </span>
    <a href="https://github.com/mkaz/hasite">Powered by Hastie</a>
</footer>

<script src="/js/asciinema/asciinema-player.js"></script>
<script src="/js/prism.js"></script>

</body>
</html>